<template>
	<a-modal :visible="visible" width="800px" class="delivery-note" :z-index="1001" title="物业交割单" centered @cancel="cancel" :maskClosable="false" :bodyStyle="{paddingBottom: 0}">
		<div class="bill-box">
			<a-select v-model:value="houseId" :options="searchOptions.houseList" :field-names="{label: 'fullAddress', value: 'id'}" class="select" @change="houseIdSelect" />
			<a-button :disabled="activeIndex === 0" @click="changeHouseId(-1)">上一套</a-button>
			<a-button :disabled="activeIndex === searchOptions.houseList.length - 1" @click="changeHouseId(1)">下一套</a-button>
		</div>
		<div class="delivery-note-module tab-box">
			<div class="d-module-title">
				<b>房屋配置</b>
			</div>
			<div class="right-btn">
				<a-button v-action="['mk_enterprise_assets_list_deploy']" type="link" @click="deliveryShow">仓库调配</a-button>
			</div>
			<vxe-grid ref="grid" v-bind="gridOptions" :data="searchOptions.houseList[activeIndex].articles">
				<template #action="{row}">
					<a v-if="hasPermissions(operation[0].action)" @click="handler(row, operation[0].field)">{{ operation[0].name }}</a>
					<a-divider type="vertical" v-if="hasPermissions(operation.map(item => item.action))" />
					<a-dropdown placement="bottom" v-if="hasPermissions(operation.map(item => item.action))">
						<a class="ant-dropdown-link">
							更多
							<down-outlined />
						</a>
						<template #overlay>
							<a-menu class="default-menu-item">
								<template v-for="(operationItem, index) in operation" :key="row.id + index">
									<a-menu-item @click="handler(row, operationItem.field)" v-if="index !== 0">{{ operationItem.name }}</a-menu-item>
								</template>
							</a-menu>
						</template>
					</a-dropdown>
				</template>
			</vxe-grid>
		</div>
		<div class="delivery-note-module">
			<div class="d-module-title">
				<b>备注</b>
			</div>
			<div>
				<a-textarea placeholder="请输入" v-model:value="searchOptions.houseList[activeIndex].comment" show-count :maxlength="100" />
			</div>
		</div>
		<div class="delivery-note-module">
			<div class="d-module-title">
				<b>水电燃气底数(只做记录)</b>
			</div>
			<vxe-table :data="[{}]" border size="small" show-overflow>
				<vxe-column v-for="meter in searchOptions.houseList[activeIndex].meters" :key="meter.deviceType" header-align="center">
					<template #header>
						{{ METER_DEVICE_MAP[meter.deviceType] }}
					</template>
					<template #default>
						<div class="display-flex">
							<a-input-number v-model:value="meter.read" size="small" :min="0" :precision="2" :controls="false" :bordered="false" placeholder="请输入底数" style="flex: 1" />
							<span style="align-self: center">{{ meter.suffix }}</span>
						</div>
					</template>
				</vxe-column>
			</vxe-table>
			<template v-if="baseNumbe.bindEleMater || baseNumbe.bindHotWaterMater || baseNumbe.bindClodWaterMater">
				<span v-if="[baseNumbe.eleMaterStatusName, baseNumbe.clodWaterMaterStatusName, baseNumbe.hotWaterMaterStatusName].includes('离线')" class="error-color">注：设备已离线，需要手动填写</span>
			</template>
		</div>
		<div class="delivery-note-module">
			<div class="d-module-title">
				<b>附件</b>
			</div>
			<div class="width-33">
				<a-button type="primary" block @click="operationField.attachment = true">
					<check-outlined v-if="attachments?.length" />
					<plus-outlined v-else />
				</a-button>
			</div>
		</div>
		<template #footer>
			<a-button @click="cancel">取消</a-button>
			<a-button type="primary" @click="sendRequest">保存</a-button>
		</template>
	</a-modal>
	<!-- 附件上传 -->
	<file-upload-dialog v-model:visible="operationField.attachment" v-model:files="searchOptions.houseList[activeIndex].attachments" />
	<!-- 选择资产 -->
	<select-delivery-order v-model:visible="delivery" :data="searchOptions.houseList[activeIndex].articles" @success="getCheckData" />
	<!-- 遗失资产 -->
	<loss-assets-dialog :data="modelData.record" v-model:visible="operationField.showLoss" @success="deleteAssetDate" />
	<!-- 报废资产 -->
	<scrap-assets-dialog :id="modelData.record.id" v-model:visible="operationField.showScrap" @success="deleteAssetDate" />
	<!-- 调配资产 -->
	<deploy-assets-dialog :id="modelData.record.id" :room-id="props.id" v-model:visible="operationField.showDeploy" @success="deleteAssetDate" />
</template>
<script setup lang="ts">
	import {reactive, ref, watch} from 'vue'
	import XEUtils from 'xe-utils'
	import {DownOutlined} from '@ant-design/icons-vue'
	import {VxeGridProps} from 'vxe-table'
	import {getCurEleAndWaterQuantity, houseConfigGetList} from '@/api/contract'
	import {CheckOutlined, PlusOutlined} from '@ant-design/icons-vue'
	import SelectDeliveryOrder from '@/components/contract/add-tenant-contract-dialog/select-delivery-order.vue'
	import LossAssetsDialog from '@/components/contract/add-tenant-contract-dialog/loss-assets-dialog.vue'
	import ScrapAssetsDialog from '@/components/contract/add-tenant-contract-dialog/scrap-assets-dialog.vue'
	import DeployAssetsDialog from '@/components/contract/add-tenant-contract-dialog/deploy-assets-dialog.vue'
	import {useStore} from '@/store/index'
	import {Img} from 'yuxin-base/src/types'
	import {METER_DEVICE_MAP} from '@/constant/device'
	import {defaultMeters} from '@/interface/contract'
	import FileUploadDialog from '@/components/common/file-upload-dialog.vue'

	const hasPermissions = useStore().hasPermissions

	const modelRef = reactive<any>({
		comment: null,
		attachments: [],
		articles: [],
		meters: defaultMeters()
	})
	const attachments = ref<Img[]>([])

	const baseNumbe = ref<any>({})
	const houseId = ref<any>('')
	const activeIndex = ref<number>(0)
	//上下切换
	const changeHouseId = num => {
		activeIndex.value = activeIndex.value + num
	}
	const houseIdSelect = () => {
		activeIndex.value = searchOptions.houseList.findIndex(o => o.id === houseId.value)
	}
	const operationField = reactive<any>({
		showLoss: false,
		showScrap: false,
		showDeploy: false,
		attachment: false
	})
	const delivery = ref<any>(false)
	const props = defineProps<{
		houseList: any
		visible: boolean
	}>()
	const checkList = reactive<any>([])

	const operation = [
		{
			name: '调配',
			field: 'deployment',
			action: ['mk_enterprise_assets_list_deploy']
		},
		{
			name: '报废',
			field: 'scrapped',
			action: ['mk_enterprise_assets_list_scrap']
		},
		{
			name: '遗失',
			field: 'lost',
			action: ['mk_enterprise_assets_list_lost']
		}
	]
	const modelData = reactive<any>({
		record: {}
	})
	const deliveryShow = () => {
		delivery.value = true
	}
	const getCheckData = (list: any) => {
		checkList.value = list
		insertEvent(list, -1)
	}
	const insertEvent = async (list: any, row: any) => {
		const $table = grid.value
		const {row: newRow} = await $table.insertAt(list, row)
		await $table.setEditCell(newRow, 'name')
		searchOptions.houseList[activeIndex.value].articles = grid.value.getTableData().tableData
	}

	const emit = defineEmits(['update:visible', 'update:houseList', 'success'])
	const cancel = () => {
		emit('update:visible', false)
	}
	const deleteAssetDate = () => {
		grid.value.remove(modelData.record)
	}
	const sendRequest = () => {
		console.log(searchOptions.houseList)
		emit('update:houseList', XEUtils.clone(searchOptions.houseList, true))
		cancel()
	}

	const handler = (row: any, type: string) => {
		modelData.record = row
		switch (type) {
			case 'deployment':
				//修改
				operationField.showDeploy = true
				console.log('调配')
				break
			case 'scrapped':
				//禁用
				console.log(modelData.record.id, 'modelData.record.id')
				operationField.showScrap = true
				console.log('报废')
				break
			case 'lost':
				//启用
				operationField.showLoss = true
				console.log('遗失')
				break
		}
	}
	const propertyList = ref<any>([])
	const grid = ref()
	const gridOptions = reactive<VxeGridProps>({
		size: 'small',
		height: '300px',
		showOverflow: true,
		rowConfig: {
			isHover: true
		},
		columns: [
			{
				title: '种类',
				minWidth: 100,
				align: 'left',
				field: 'typeName'
			},
			{
				title: '物品名称',
				minWidth: 100,
				align: 'left',
				field: 'configName'
			},
			{
				title: '价格(元)',
				minWidth: 80,
				align: 'left',
				field: 'price'
			},
			{
				title: '数量',
				minWidth: 50,
				align: 'center',
				field: 'count'
			},
			{
				title: '操作',
				width: 120,
				align: 'center',
				slots: {
					default: 'action'
				}
			}
		]
	})

	const searchOptions = reactive<any>({
		houseList: [{}]
	})
	watch(
		() => props.visible,
		(newVal, oldVal) => {
			if (newVal) {
				if (props.houseList.length) {
					houseId.value = props.houseList[0].id
					searchOptions.houseList = props.houseList
					searchOptions.houseList.forEach(item => {
						item.meters = item.meters || defaultMeters()
						item.comment = item.comment || null
						item.attachments = item.attachments || []
						item.articles = item.articles || []
					})
					activeIndex.value = 0
				}
			}
		}
	)
	// 重置表单
	const formRef = ref<any>()
</script>
<style lang="less">
	.bill-box {
		// position: fixed;
		display: flex;
		justify-content: space-around;
		margin-bottom: 10px;
		.select {
			width: 888px;
		}
	}
	.width-33 {
		width: 33.33%;
	}
	.delivery-note .ant-modal-content {
		.ant-modal-body {
			height: 600px;
			overflow-y: auto;
		}

		.tab-box {
			position: relative;

			.right-btn {
				position: absolute;
				right: 0;
				top: 0;
			}
		}

		.d-module-title {
			margin-bottom: 5px;
		}
		.delivery-note-module {
			margin-bottom: 20px;
		}
	}
</style>
